/*2S7LXljdWdGhrCxZ1MFl4sY6vVudd5AlfFGXc2wfurWulfL1S++K0/y714pyGT2I*/
/* 盘点单卡片界面 */
import React, { Component } from 'react';
import { createPage, base, high, createPageIcon, cardCache } from 'nc-lightapp-front';
import {
	buttonClick,
	StepOne,
	StepTwo,
	StepThree,
	initTemplate,
	AnewAllot,
	InventoryResult,
	backToList,
	DetailList,
	pageInfoClick,
	commit
} from './events';
import { pageConfig } from './const';
import './index.less';
import constant from '../constants';
import ampub from 'ampub';
const { components, commonConst, utils } = ampub;
const { cardUtils, multiLangUtils, closeBrowserUtils, listUtils } = utils;
const { getTitleName } = listUtils;
const { getMultiLangByID } = multiLangUtils;
const { createCardPaginationArea, creatCardSocket } = cardUtils;
const { CommonKeys } = commonConst;
const { linkQueryConst } = CommonKeys;
const { ApprovalTrans, CrossServiceCardBtn } = components;
let { SagaStatus } = ampub.commonConst.SagaConst;
const { NCStep, NCAffix, NCBackBtn, NCDiv } = base;
const { title, pagecode, dataSource, area, formId, pkField, bill_type } = pageConfig;
const { NCSteps } = NCStep;
import ApproveDetail from 'uap/common/components/ApproveDetail';
import CreateNCUploade from 'uap/common/components/CreateNCUploade';
const { createNCUploader } = CreateNCUploade;
const steps = [
	{ title: getMultiLangByID('201203004A-000046') /*确定盘点范围*/ },
	{ title: getMultiLangByID('201203004A-000047') /*分配盘点人*/ },
	{ title: getMultiLangByID('201203004A-000048') /*确认*/ }
];

/**
 * 资产盘点
 * @author : liuzjk 
 */
class Maininfo extends Component {
	constructor(props) {
		props.use.search(constant.AREA.STEP.INVENTORY_RANGE);
		props.use.form(formId, constant.AREA.STEP.INVENTORY_DATE);
		props.use.cardTable(constant.AREA.STEP.ANEWALLOT, constant.AREA.STEP.DETAIL_LIST);
		props.use.editTable(constant.AREA.STEP.ALLOT_CHECKUSER);
		super(props);
		// 是否从列表跳转的
		this.isFromList = 'false';
		// 单据号
		this.bill_code = null;
		// 盘点结果组织
		this.result_pk_org = '';
		// 时间戳
		this.ts = '';
		// 盘点范围
		this.rangeAreaData = null;
		// 标识符
		this.signature = '';
		/* 盘点结果 */
		this.checkResult = '0';
		// 临时存储分配盘点人数据
		this.tempEditTableDatas = null;
		// 临时存储未分配盘点人数据
		this.tempCardTableDatas = [];
		this.echartsData = {
			total_num: 0,
			start_date: 0,
			end_date: 0,
			pk_org: '',
			pk_category: '',
			/* 盘点范围 */
			check_range: '',
			/* 查询区范围 */
			search_range: {},
			/**
			 * 饼图数据
			 */
			pie_data: {
				category_total: [],
				values: []
			},
			/**
			 * 盘点结果柱状图数据
			 */
			bar_data: {
				x_axis: [],
				unfinished: [],
				finished: []
			},
			/**
			 * 确定后柱状图数据
			 */
			linedata: {
				data: [],
				name: []
			}
		};
		/**
		 * 保存成功后从服务返回的数据
		 */
		this.childformData = {
			head: [],
			body: [],
			way: []
		};
		this.state = {
			// bill_code: '',
			pk_inventory: '',
			pk_reduce: '',
			pk_profit: '',
			pk_alter: '',
			bill_status: '', //单据状态
			current: 0, //步骤条对应页面的参数默认：0
			inventoryWay: 1, //步骤二中分配盘点方式的值
			inventoryStatus: 'default',
			pk_bill: '',
			showApprove: false,
			/* 提交指派 */
			compositedisplay: false,
			compositedata: {},
			transi_type: '',
			isLeaveOrRefresh: false,
			billInfo: {
				//单据信息
				isError: false
			},
			uploader: {}
		};
		closeBrowserUtils.call(this, props, {
			editTable: [ constant.AREA.STEP.ALLOT_CHECKUSER ],
			cardTable: [ constant.AREA.STEP.DETAIL_LIST ]
		});
		initTemplate.call(this, props);
	}

	//提交及指派 回调
	getAssginUsedr = (value) => {
		commit.call(this, 'SAVE', this.props, value);
	};
	//取消 指派
	turnOff = () => {
		this.setState({
			compositedisplay: false
		});
	};
	//步骤条详细说明
	Ondescription = (current, index) => {
		if (index == current) {
			return getMultiLangByID('201203004A-000049') /*进行中*/;
		} else if (index < current) {
			return getMultiLangByID('201203004A-000050') /*已完成*/;
		} else {
			return;
		}
	};

	/**
	 * 头部显示数据控制
	 * 		1.返回按钮
	 * 		2.标题
	 * 		3.盘点单号
	 */
	createCardTitleArea = (current) => {
		/**************************************** 
		 *flag:返回按钮是否显示标识
		 *条件：查看盘点结果 或 第三步保存后 或 盘点明细（盘点结果穿透列表）
		 *		并且 非审批小应用 并且 非盘点报告穿透
		 ****************************************/
		let flag =
			((current === 3 || current === 7) &&
				this.props.getUrlParam('scene') != linkQueryConst.SCENETYPE.approvesce) /* 非审批小应用 */ ||
			current === 6; // 盘点明细不管是审批小应用还是非审批小应用，都应该有返回按钮
		/* 单据号 是否显示 */
		let bill_code = this.bill_code;
		let titleValue = getTitleName.call(this, this.props);
		if (bill_code) {
			titleValue = getTitleName.call(this, this.props) + ':' + bill_code;
		}
		return (
			<div className="header-title-search-area org-content">
				{flag && (
					<NCBackBtn
						// className="title-search-detail"
						onClick={() => {
							backToList.call(this, this.props, current);
						}}
						fieldid="back_btn"
					/>
				)}
				{createPageIcon()}
				<h2 fieldid={getTitleName.call(this, this.props) + '_title'} className="title-search-detail">
					{titleValue}
				</h2>
			</div>
		);
	};

	socketMessageHandle = (props, msg) => {
		let billInfo = msg.refreshData && msg.refreshData[0];
		if (msg.error && billInfo) {
			let saga_status = billInfo.saga_status;
			this.setState({
				billInfo: {
					isError: SagaStatus.errorValue === saga_status,
					gtxid: billInfo.saga_gtxid,
					billpk: billInfo[pkField]
				}
			});
		} else {
			// 事务通过重试或回退方式成功时，要恢复按钮显示控制逻辑
			this.setState({
				billInfo: {
					isError: false
				}
			});
		}
		//更新列表态缓存
		let cachedData = cardCache.getCacheById(billInfo[pkField], constant.DATASOURCE);
		if (cachedData) {
			let headValue = cachedData.head[constant.AREA.CARD.BODY_HEAD].row[0].values;
			Object.keys(billInfo).forEach((key) => {
				if (headValue[key]) {
					headValue[key].value = billInfo[key];
				}
			});
			cardCache.updateCache(
				pkField,
				billInfo[pkField],
				cachedData,
				constant.AREA.CARD.BODY_HEAD,
				constant.DATASOURCE
			);
		}
	};

	render() {
		let { ncmodal, button } = this.props;
		let { current, inventoryStatus, showApprove, pk_inventory, transi_type } = this.state; // 需要输出的数据
		let { createModal } = ncmodal;
		let { createButtonApp, createErrorFlag } = button;
		let isSagaError = this.state.billInfo && this.state.billInfo.isError;

		return (
			<div className="nc-bill-card fa-inventory">
				{/* <div className="nc-bill-top-area"> */}
				<NCAffix>
					{/* 头部 header */}
					<NCDiv
						areaCode={NCDiv.config.HEADER}
						className={'nc-bill-header-area nonprint' + (isSagaError ? ' socket-error-class ' : '')}
					>
						<div className="header-title-search-area">{this.createCardTitleArea.call(this, current)}</div>

						{/* 按钮区 btn-area */}
						<div className="header-button-area">
							{/* 创建重试、回退等 saga 状态按钮 */}
							<CrossServiceCardBtn billInfo={this.state.billInfo} />
							{createButtonApp({
								area: 'card_head',
								buttonLimit: 3,
								onButtonClick: buttonClick.bind(this),
								popContainer: document.querySelector('.header-button-area')
							})}
						</div>

						{current == 7 &&
							inventoryStatus == 'confirmed' &&
							createCardPaginationArea.call(this, this.props, {
								formId,
								dataSource,
								pageInfoClick
							})}
					</NCDiv>
				</NCAffix>
				{/* </div> */}
				<div className="nc-bill-table-area">
					<div
						className={`current-content-area nc-theme-area-bgc ${this.state.current === 1 &&
							'stepTwo-content-area'}`}
					>
						{this.state.current < 4 && (
							<div className="step-area">
								<NCSteps current={current}>
									{steps.map((item, index) => (
										<NCStep
											key={item.title}
											title={item.title}
											description={this.Ondescription(current, index)}
										/>
									))}
								</NCSteps>
							</div>
						)}
						{this.state.current === 0 && <StepOne {...this.props} rangeAreaData={this.rangeAreaData} />}
						{this.state.current === 1 &&
							(inventoryStatus === 'confirmedAllot' || inventoryStatus === 'unAllot' ? (
								<AnewAllot {...this.props} />
							) : (
								<StepTwo {...this.props} echartsData={this.echartsData} that={this} />
							))}
						{(this.state.current === 2 || this.state.current === 3) && (
							<StepThree {...this.props} echartsData={this.echartsData} that={this} />
						)}
						{this.state.current === 6 && <DetailList {...this.props} that={this} />}
						{this.state.current === 7 &&
							(inventoryStatus === 'confirmedAllot' ? (
								<AnewAllot {...this.props} />
							) : (
								<InventoryResult {...this.props} echartsData={this.echartsData} that={this} />
							))}
					</div>
				</div>
				{/* 确认取消框 */}
				{createModal(`${pagecode}-confirm`, { color: 'warning' })}
				{/* 审批详情 */}
				<ApproveDetail
					show={showApprove}
					close={() => {
						this.setState({ showApprove: false });
					}}
					billtype={transi_type}
					billid={pk_inventory}
				/>
				{/* 提交及指派 */}
				{this.state.compositedisplay ? (
					<ApprovalTrans
						title={getMultiLangByID('amcommon-000002') /*指派*/}
						data={this.state.compositedata}
						display={this.state.compositedisplay}
						getResult={this.getAssginUsedr}
						cancel={this.turnOff}
					/>
				) : (
					''
				)}
				{/* 附件管理框 */}
				{createNCUploader.call(this, `${pagecode}-uploader`, {})}

				{/* 创建 socket 链接 */}
				{creatCardSocket.call(this, this.props, {
					headBtnAreaCode: 'card_head', // 按钮区域编码,用于平台内部更新按钮状态
					billpkname: pkField, //单据主键名, 用于查询追溯
					billtype: bill_type, //单据类型, 用于查询追溯
					onMessage: this.socketMessageHandle.bind(this)
				})}
			</div>
		);
	}
}

const MasterChildCardBase = createPage({
	billinfo: {
		billtype: 'grid',
		pagecode: pagecode, // 页面编码
		bodycode: area.card.body_area, //表体编码
		tabletype: 'cardTable'
	}
})(Maininfo);

export default MasterChildCardBase;

/*2S7LXljdWdGhrCxZ1MFl4sY6vVudd5AlfFGXc2wfurWulfL1S++K0/y714pyGT2I*/